package com.sk.z.khk.googleplace;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class GPJsonOperator {

	private ObjectMapper om = new ObjectMapper();

	public GPJsonOperator() {
	}

	public Map<String, Object> transformJsonStringAsMap(String jsonStr) {
		Map<String, Object> m = null;
		try {
			m = om.readValue(jsonStr, new TypeReference<Map<String, Object>>() {
			});
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return m;
	}

	public Map<String, Object> createGPMap() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("html_attributions", new ArrayList<Map<String, Object>>());
		map.put("results", new ArrayList<Map<String, Object>>());
		map.put("status", new String("OK"));
		return map;
	}

	public Map<String, Object> addResultElement(Map<String, Object> newMap,
			Map<String, Object> target) {
		List<Map<String, Object>> results = getResults(newMap);

		Map<String, Object> targetLocation = getLocation(getGeometry(target));
		boolean isDuplication = contains(results, targetLocation);
		if (!isDuplication)
			results.add(target);
		return newMap;
	}

	public boolean contains(List<Map<String, Object>> results,
			Map<String, Object> targetLocation) {
		for (Map<String, Object> result : results) {
			Map<String, Object> location = getLocation(getGeometry(result));
			if (location.get("lat").equals(targetLocation.get("lat")))
				if (location.get("lng").equals(targetLocation.get("lng")))
					return true;
		}
		return false;
	}

	public Map<String, Object> getResult(List<Map<String, Object>> results,
			int i) {
		return results.get(i);
	}

	public Map<String, Object> getGeometry(Map<String, Object> result) {
		return ((Map<String, Object>) result.get("geometry"));
	}

	public Map<String, Object> getLocation(Map<String, Object> geometry) {
		return ((Map<String, Object>) geometry.get("location"));
	}

	public List<Map<String, Object>> getResults(Map<String, Object> root) {
		return ((List<Map<String, Object>>) root.get("results"));
	}

	public void writeValue(PrintWriter writer, Map<String, Object> map) {
		try {
			om.writeValue(writer, map);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
